package mbp.gui.panels;

import javax.swing.JPanel;
import mbp.base.FeatureType;
import mbp.base.ResourceType;
import mbp.core.Offer;
import mbp.core.Resource;
import mbp.core.ResourceValidation;
import mbp.exceptions.InvalidFeatureNameException;
import mbp.gui.base.EachRowEditor;

import javax.swing.border.TitledBorder;
import javax.swing.table.DefaultTableModel;
import javax.swing.UIManager;
import java.awt.Color;
import javax.swing.JScrollPane;
import java.awt.Component;
import javax.swing.JButton;
import java.awt.Font;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import java.util.ArrayList;
import java.util.Iterator;

import javax.swing.DefaultCellEditor;
import javax.swing.JLabel;
import javax.swing.JTable;
import javax.swing.JTextField;
import javax.swing.JComboBox;

public class OfferDetailsPanel extends JPanel 
{
	//private JPanel panel;
	
	private Offer offer;
	private JComboBox cmbOut;
	private ArrayList<Resource> serviceRcOut; //Lista na zasoby wyjsciowe aktywnego serwisu
	private ArrayList<Integer> serviceRcOutTerm;
	
	private JTable tdOut;
	private JTable tdIn;
	private DefaultTableModel modelOut, modelIn;
	private JTextField txtOutTerm;
	private JTextField txtRealizeTerm;
	
	//private OfferInfoPanel offerInfoPanel;

	/**
	 * Create the panel.
	 */
	public OfferDetailsPanel() 
	{
		serviceRcOut = new ArrayList<Resource>();
		serviceRcOutTerm = new ArrayList<Integer>();
		//this.setTitle("Offer for service: " + offer.getServiceType().GetServiceTypeName() +
		//		      " from: " + offer.getServerName());
		//setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
		//setBounds(100, 100, 700, 453);
		//panel = new JPanel();
		//setContentPane(contentPane);
		setLayout(null);
		
		//offerInfoPanel = new OfferInfoPanel();
		//offerInfoPanel.setBounds(10, 11, 674, 122);
		//offerInfoPanel.setBorder(new TitledBorder(UIManager.getBorder("TitledBorder.border"), "Offer info", TitledBorder.LEADING, TitledBorder.TOP, null, new Color(0, 0, 0)));
		//add(offerInfoPanel);
		
		
		//JPanel panel_0 = new JPanel();
		//setLayout(null);
		//setBorder(new TitledBorder(UIManager.getBorder("TitledBorder.border"), "Offer details", TitledBorder.LEADING, TitledBorder.TOP, null, new Color(0, 0, 0)));
		//setBounds(10, 11, 674, 270);
		//add(panel_0);
		
		JScrollPane scrollPane1 = new JScrollPane((Component) null);
		scrollPane1.setBounds(10, 155, 270, 76);
		add(scrollPane1);
		
		modelOut = new DefaultTableModel();
		modelOut.addColumn("Feature Name");
		modelOut.addColumn("Feature Type");
		modelOut.addColumn("Feature Value");
		tdOut = new JTable(modelOut);
		tdOut.setFillsViewportHeight(true);
		scrollPane1.setViewportView(tdOut);
		
		JButton btnSet = new JButton("Set");
		btnSet.setName("SET");
		btnSet.setFont(new Font("Arial", Font.PLAIN, 11));
		btnSet.setBounds(583, 208, 79, 23);
		add(btnSet);
		
		JLabel label_1 = new JLabel("Out");
		label_1.setBounds(10, 141, 46, 14);
		add(label_1);
		
		cmbOut = new JComboBox();
		cmbOut.setBounds(290, 155, 107, 22);
		add(cmbOut);
		
		JScrollPane scrollPane2 = new JScrollPane();
		scrollPane2.setBounds(10, 30, 652, 100);
		add(scrollPane2);
		
		modelIn = new DefaultTableModel();
		modelIn.addColumn("Index");
		modelIn.addColumn("Type");
		modelIn.addColumn("Condition");
		modelIn.addColumn("Quantity");
		modelIn.addColumn("Term");
		tdIn = new JTable(modelIn);
		tdIn.setFillsViewportHeight(true);
		//tdIn.getColumnModel().getColumn(0).setPreferredWidth(50);
		scrollPane2.setViewportView(tdIn);
		
		JLabel label_2 = new JLabel("In");
		label_2.setBounds(10, 15, 35, 15);
		add(label_2);
		
		txtOutTerm = new JTextField();
		txtOutTerm.setBounds(407, 155, 107, 22);
		add(txtOutTerm);
		txtOutTerm.setColumns(10);
		
		JLabel lblValidity = new JLabel("Validity term");
		lblValidity.setBounds(407, 141, 107, 14);
		add(lblValidity);
		
		JLabel lblType = new JLabel("Type");
		lblType.setBounds(290, 141, 46, 14);
		add(lblType);
		
		txtRealizeTerm = new JTextField();
		txtRealizeTerm.setBounds(555, 155, 107, 22);
		add(txtRealizeTerm);
		txtRealizeTerm.setColumns(10);
		
		JLabel lblRealizeTerm = new JLabel("Realize term");
		lblRealizeTerm.setBounds(555, 141, 107, 14);
		add(lblRealizeTerm);
		
		cmbOut.addItemListener(new ItemListener() {
			
			@Override
			public void itemStateChanged(ItemEvent arg0) {
				int index = cmbOut.getSelectedIndex();
				loadresourceOut(serviceRcOut, serviceRcOutTerm, index);
			}
		});
	}
	
	public void loadOffer(Offer cntr)
	{
		this.offer = cntr;
		
		int rowsCount = 0;
		//System.out.println("Service type name: " + srv.getServiceType().GetServiceTypeName());
		//ArrayList<ResourceType> types_in = (ArrayList<ResourceType>) srv.getServiceType().getResourceTypesIn();
		ArrayList<Resource> types_out = (ArrayList<Resource>) cntr.getResourcesOut();
		ArrayList<Integer> types_out_term = (ArrayList<Integer>) cntr.getResourcesOutValidTerms();
		
		ArrayList<ResourceValidation> valInAdvance = cntr.getResourcesIn(0);
		ArrayList<ResourceValidation> valInStuff = cntr.getResourcesIn(1);
		ArrayList<ResourceValidation> valInPay = cntr.getResourcesIn(2);
		
		/**
		 * Wyczyszczenie tabeli
		 */
		for( int i = modelIn.getRowCount() - 1; i >= 0; i-- )
		{
		    modelIn.removeRow(i);
		}
		
		//Zasoby zaliczka
		for(int i = 0; i<valInAdvance.size(); i++)
		{
			modelIn.insertRow(i, new Object[]{"advance", 
					valInAdvance.get(i).getType().getResourceTypeName(),
					cntr.getResourcesIn(0).get(i).getCondition(),
					cntr.getResourcesIn(0).get(i).getQuantity().toString(),
					"-"});
		}
		rowsCount = valInAdvance.size();
		
		//Zasoby towar
		for(int i = 0; i<valInStuff.size(); i++)
		{
			modelIn.insertRow(i+rowsCount, new Object[]{"stuff", 
					valInStuff.get(i).getType().getResourceTypeName(), 
                    cntr.getResourcesIn(1).get(i).getCondition(),
                    cntr.getResourcesIn(1).get(i).getQuantity().toString(),
                    cntr.getResourcesInDeliveryTrems().get(i).toString()});
			
		}
		rowsCount = rowsCount + valInStuff.size();
		
		//zasoby zaplata
		for(int i = 0; i<valInPay.size(); i++)
		{
			modelIn.insertRow(i+rowsCount, new Object[]{"pay", 
					valInPay.get(i).getType().getResourceTypeName(), 
                    cntr.getResourcesIn(2).get(i).getCondition(),
                    cntr.getResourcesIn(2).get(i).getQuantity().toString(),
                    cntr.getServiceRealizeTerm().toString()});
			
		}
		
		txtRealizeTerm.setText(cntr.getServiceRealizeTerm().toString());
		
		cmbOut.removeAllItems();
		//serviceRcOut = new ArrayList<Resource>();
		for(int i = 0; i<types_out.size(); i++)
		{
			//cmbOut.addItem(types_out.get(i).GetType().GetResourceTypeName());
			serviceRcOut.add(types_out.get(i));
			serviceRcOutTerm.add(types_out_term.get(i));
			cmbOut.addItem(types_out.get(i).getType().getResourceTypeName());
		}
		

		//tdIn.getColumnModel().getColumn(0).setMinWidth(60);
		//tdIn.getColumnModel().getColumn(0).setMaxWidth(60);
		//tdIn.getColumnModel().getColumn(1).setMinWidth(70);
		//tdIn.getColumnModel().getColumn(1).setMaxWidth(100);
		tdIn.getColumnModel().getColumn(2).setMinWidth(450);
		tdIn.getColumnModel().getColumn(2).setMaxWidth(450);
	}
	
	
	public void loadresourceOut(ArrayList<Resource> rcOutList, ArrayList<Integer> rcOutTermList, int index)
	{
		if(index == -1)return;
		
		int rowsCount = 0;
		/**
		 * Wyczyszczenie tabeli
		 */
		for( int i = modelOut.getRowCount() - 1; i >= 0; i-- )
		{
		    modelOut.removeRow(i);
		}
		
		Resource rcOut = rcOutList.get(index);
		Integer rcOutTerm = rcOutTermList.get(index);
		ResourceType resType = rcOut.getType();
		
		/**
		 * Utworzenie tabeli JTable dt pozwalajecej wrowadzic wartosci cech utworzonego zasobu
		 */
		Iterator it = rcOut.getType().getFeaturesCollection().keySet().iterator();
		while (it.hasNext()) 
		{
			String key = (String)it.next();
			//System.out.println("f: " + key);
			//rowsCount = dt.getRowCount();
			try
			{
				FeatureType type = rcOut.getFeatureType(key);
				Object ob = rcOut.getFeatureValue(key);
				if(ob==null)
				{
					modelOut.insertRow(rowsCount, new Object[]{key,  rcOut.getFeatureType(key), null});
				}
				else
				{
					switch(type)
					{
					case INT:
						modelOut.insertRow(rowsCount, new Object[]{key,  rcOut.getFeatureType(key), ((Integer)ob).toString()});						
						break;
					case FLOAT:
						modelOut.insertRow(rowsCount, new Object[]{key,  rcOut.getFeatureType(key), ((Float)ob).toString()});
						break;
					default:
						modelOut.insertRow(rowsCount, new Object[]{key,  rcOut.getFeatureType(key), ob.toString()});
						break;
					}
				}
				
				rowsCount++;
			}
			catch (InvalidFeatureNameException ex)
			{
				//logger.error("InvalidFeatureNameException", ex);
			} 
		}
		
		txtOutTerm.setText(rcOutTermList.get(index).toString());
		
		
		/**
		 * DLA TYPOW ENUM
		 * Modyfikacja komorek tabeli (danego wiersza) aby mozna bylo wyswietlic obiekt JComboBox
		 */
		EachRowEditor rowEditor = new EachRowEditor(tdOut);
		for(int i = 0; i<tdOut.getRowCount(); i++)
		{
			if(tdOut.getValueAt(i, 1) == FeatureType.ENUM)
			{
				/**
				 * Utworzenie obiektu JComboBox wartosci enum przylkadowego typu
				 * Obiekt ten zostanie umieszczony w tabeli
				 */
				JComboBox cmbTypesV = new JComboBox();
					String[] ev = resType.getEnumTypes().get((String)tdOut.getValueAt(i, 0)).getArray();
					
					for(String v: ev)
					{
						cmbTypesV.addItem(v);
					}
				rowEditor.setEditorAt(i, new DefaultCellEditor(cmbTypesV));
							
			}
			tdOut.getColumn("Feature Value").setCellEditor(rowEditor);
		}		
	}
}
